﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace Mozhi.Abp.Core.Extensions
{
    public static class DateTimeExtension
    {
        public static int ToPeriod(this DateTime date)
        {
            if(date ==default)
                throw new ArgumentNullException("date");

            return date.Year * 100 + date.Month;
        }

        public static int ToPrePeriod(this int period)
        {
            var parsedDate = DateTime.MinValue;

            if (!DateTime.TryParseExact(period + "01", "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                throw new Exception("获取上一期失败，非法的期间:" + period);

            var preDate = parsedDate.AddMonths(-1);

            return preDate.Year * 100 + preDate.Month;
        }

        public static int ToNextPeriod(this int period)
        {
            var parsedDate = DateTime.MinValue;

            if (!DateTime.TryParseExact(period + "01", "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                throw new Exception("获取上一期失败，非法的期间:" + period);

            var nextDate = parsedDate.AddMonths(1);

            return nextDate.Year * 100 + nextDate.Month;
        }

        public static DateTime ToLastDayDateTime(this int period)
        {
            var parsedDate = DateTime.MinValue;

            if (!DateTime.TryParseExact(period + "01", "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                throw new Exception("非法的期间:" + period);

            var lastDay = parsedDate.Day;

            return parsedDate.AddDays(lastDay - 1);
        }

        public static DateTime ToLastDayDateTime(this DateTime date)
        {
            var lastDay = date.Day;

            return new DateTime(date.Year, date.Month, lastDay);
        }

        public static DateTime ToFirstDayDateTime(this int period)
        {
            var parsedDate = DateTime.MinValue;

            if (!DateTime.TryParseExact(period + "01", "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                throw new Exception("非法的期间:" + period);

            return parsedDate;
        }

        public static DateTime ToFirstDayDateTime(this DateTime date)
        {
            return new DateTime(date.Year, date.Month, 1);
        }

        public static int DifferencePeriod(this int period , int endPeriod)
        {
            var endDate = endPeriod.ToLastDayDateTime();

            var startDate = period.ToLastDayDateTime();

            return ((endDate.Year - startDate.Year) * 12) + endDate.Month - startDate.Month;
        }
    }
}
